var cf = require("../../config.js");
var cf2 = require("../../utils/config2");
var util = require("../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../template/baseHandle.js");
var commHandle = require("../template/commHandle.js");
var regeneratorRuntime = require("../../lib/js/runtime-module");
var changeTime = require("../../utils/changetime.js");
var webim = global.webim;
var webimhandler = global.webimhandler;
var selToID = "";
var userSignInfo = null;
var card_id = "";
//获取应用实例
var app = getApp();
Page(Object.assign({}, baseHandle, commHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    getPhoneNumber: false,
    skipUserInfoOauth: true,
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    shareMask: false,
    card_detail_noread: 0,
    card: {},
    address: '',//默认给 公司地址， 如果通过queryDetail 查出销售员有重新设置 则显示自定义的地址
    isLocation: false,
    isThumbs: false,
    isSales: false,
    showNavBar:true,
    adInfo: { show: false },
    isOpen: false,//播放开关
    starttime: '00:00', //正在播放时长
    duration: '00:00', //总时长,
    isFirstIn: true,
    memberCount: 0,
    reGoodList: [],
    cardStyleId: 1,
    addingFlag: false,
    thumbsIng: false,
    recommendList: [],
    opentype: 1,
    redpackShow: false, //可用红包
    redPackData: "",
    eId: '',
    activityList: [],
    couponList: [],
    houseList: [],
    opa: 0,
    num: -0.6,
    latitude: '',
    longitude: '',
    showChatBtn:true,
    defaultImg:'https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/card/card_defaultImg.png',
    isDimission:false
  },
  /**
  * 获取顾问的最新楼盘
  */
  getNewestProduct(phone,cb) {
    let that = this;
    wx.request({
      url: `${cf2.default.dataCenter}/zmzj/product/newest/${phone}`,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('authName')
      },
      success: function (res) {
        if(cb)cb(res.data.data)
      }
    })
  },
  toInforList(){
    wx.navigateTo({url:`/subPackages2/pages/InformationList/InformationList?mobile=${this.data.card.phone}&pageType=card`})
  },
  initIM: function (callback) {
    var that = this;
    userSignInfo = wx.getStorageSync("IMUserSignInfo");
    that.setData({
      userSignInfo: userSignInfo
    })
    webimhandler.init({
      accountMode: 0
      , accountType: userSignInfo.imAccountType
      , identifier: userSignInfo.identifier
      , userSig: userSignInfo.sign
      , sdkAppID: userSignInfo.imAppId
      , selType: webim.SESSION_TYPE.C2C
      , selToID: that.data.toUserSignInfo.identifier
      , selSess: null //当前聊天会话
    });
    webimhandler.setNewMsgListener(function (newmsg) {
      if (newmsg.fromAccount == that.data.toUserSignInfo.identifier) {
        var chat_content = that.data.chat_content;
        var r = newmsg.elems[0].content.text;
        var d = JSON.parse(util.chageChatData2(r));
        var u = {
          type: 0,
          head_img: that.data.toUserSignInfo.headUrl,
          from_userinfo: that.data.userSignInfo,
          to_userinfo: that.data.toUserSignInfo, card_id: card_id,
          msg: d.msg,
          date: changeTime.getChatTimer(h.nowdate(newmsg.time * 1000, 1))
        };
        chat_content.push(u);
        that.setData({
          chat_content: chat_content,
          toview: "m" + (chat_content.length - 1)
        });
      }
      console.log(newmsg);
    });
    callback && callback();
  },
  fetchSig: function (openid, cb) {
    let that = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/sign/getUserSign",
      data: {
        cusmallToken: wx.getStorageSync('cusmallToken'),
        identifier: openid
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data && 0 == res.data.ret) {
          res.data.model.headUrl= res.data.model.headUrl?res.data.model.headUrl:that.data.defaultImg
          that.setData({
            toUserSignInfo: res.data.model
          })
          selToID = res.data.model.identifier;
          cb && cb(res.data.model);
        } else if (res.data && 4000 == res.data.ret) {
          wx.navigateTo({
            url: '/subPackages/pages/login/login'
          })
        }else {
           wx.showModal({
             title: '提示',
             showCancel: false,
             content: "数据加载失败，请联系负责人"
           })
        }
      }
    });
  },
  setOpa: function () {
    let that = this
    let add = function (num) {
      that.setData({
        opa: (num + 0.3) > 1 ? 1 : ((num + 0.3) < 0 ? 0 : Number((num + 0.3).toFixed(1))),
        num: Number((num + 0.3).toFixed(1))
      })
    }
    let reduce = function (num) {
      that.setData({
        opa: (num - 0.3) < 0 ? 0 : ((num - 0.3) > 1 ? 1 : Number((num - 0.3).toFixed(1))),
        num: Number((num - 0.3).toFixed(1))
      })
    }
    let setNum = add;
    setInterval(() => {
      // console.log(that.data.opa)
      if (that.data.num == -0.6) {
        setNum = add
      }
      if (that.data.num == 1.2) {
        setNum = reduce
      }
      setNum(that.data.num);
    }, 1000);
  },

  // 点我导航
  showLocation: function () {
    console.log(this.data.latitude)
    if (this.data.eId) {
      util.addBehaviorTrail(this.data.eId, 53);
    }
    // 等待后台返回经纬度
    wx.openLocation({
      latitude: this.data.latitude,
      longitude: this.data.longitude
    })
  },
  // 名片码跳转
  toTab: function (e) {
    const data = e.currentTarget.dataset
    wx.navigateTo({ url: `/subPackages/pages/qrcode/qrcode?name=${data.name}&position=${data.position}&eid=${data.eid}&headPic=${data.headpic}` })
  },
  //开始播放
  audioPlay: function () {
    var ctx = this;
    this.audioCtx.play()
    this.setData({
      isOpen: true
    })
    util.addBehaviorTrail(ctx.data.eId,24);
  },
  /*获取活动*/
  getActivity: function (phone) {
    console.log(phone)
    let that = this;
    wx.request({
      //url: `http://10.73.158.97:8097/zmzj/activity/${phone}/1/10`,
      url: `${cf2.default.dataCenter}zmzj/activity/${phone}/1/10`,
      header: {
        'content-type': 'application/json',
        'token':wx.getStorageSync('authName')
      },
      success: function (res) {
        console.log('activityList', res)
        that.setData({ activityList: res.data.data?res.data.data.list:''})
      }
    })
  },
  /*获取优惠券*/
  getcouponList(phone) {
    let that = this;
    wx.request({
      url: `${cf2.default.dataCenter}zmzj/coupon/${phone}`, //'http://10.73.159.105:8097/zmzj/coupon/15940067368',//
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('authName')
      },
      success: function (res) {
        console.log(res.data);
        let couponList = []
        for (let key in res.data) {
          //res.data[key].productId = key;
          if (res.data[key].data && res.data[key].data.length) {
            res.data[key].data.map(item => {
              item.productId = key;
              couponList.push(item);
            })
          }
        }
        that.setData({ couponList })
      }
    })
    console.log(this.data.couponList)
  },
  /** 获取咨询*/
  getNews(phone) {
    let that = this;
    wx.request({
      //url:`http://10.73.158.97:8097/zmzj/news/${phone}/1/9999`,
      url: `${cf2.default.dataCenter}zmzj/news/${phone}/1/9999`,
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('authName')
      },
      success(res) {
        that.setData({
          newList: res.data.data?res.data.data.list:''
        })
      }
    })
  },

  /**领取优惠券 */
  receiveCoupon(e) {
    let that = this;
    wx.request({
      url: `${cf2.default.host}/app/coupons/create`,
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('authName')
      },
      data: {
        couponsConfigId: e.detail.id
      },
      success(res) {
        let {id,amount,name,type} = e.detail
        let couponName = ''
        if(type==1){
          couponName = '￥'+(amount)+'-'+name
        }else{
          couponName = (amount*10)+'折券-'+name
        }
        that.getcouponList(that.data.card.phone);
        util.addBehaviorTrail(that.data.eId, 57,id,couponName);
        wx.showToast({ title: "领取成功" });
      },
      fail(err) {
        wx.showToast({ title: result.msg != 'null' ? result.msg : '领取失败', icon: "none" });
      }
    })
  },
  /** 跳转资讯详情*/
  toInformationDetail(e) {
    let { id, name } = e.currentTarget.dataset;
    wx.navigateTo({ url: `../../subPackages/pages/InformationDetail/InformationDetail?id=${id}&name=${name}` })
  },
  /*关闭提示框*/
  CloseTips: function () {
    console.log(app.globalData);
    app.globalData.firstInTips = false;
    this.setData({
      "firstInTips": false
    })
  },
  //暂停播放
  audioPause: function () {
    this.audioCtx.pause()
    this.setData({
      isOpen: false
    })
  },

  //拖动进度条
  sliderChange(e) {
    var offset = parseInt(e.detail.value);
    this.audioCtx.seek(offset);
  },

  //监听播放时长
  updata(e) {
    console.log(e);
    var that = this;
    var target = e.currentTarget.dataset.type;
    var duration = e.detail.duration; //总时长
    var offset = e.detail.currentTime; //当前播放时长
    var currentTime = parseInt(e.detail.currentTime);
    var min = "0" + parseInt(currentTime / 60);
    var max = "0" + parseInt(e.detail.duration / 60);
    var durationmax = parseInt(e.detail.duration);
    var sec = currentTime % 60;
    var sexmax = parseInt(e.detail.duration) % 60;

    if (sec < 10) {
      sec = "0" + sec;
    };
    if (sexmax < 10) {
      sexmax = "0" + sexmax;
    };
    console.log(target);
    var starttime = min + ':' + sec; /* 00:00 */
    var durationtime = max + ':' + sexmax
    that.setData({
      offset: currentTime,
      starttime: starttime,
      duration: durationtime,
      max: durationmax
    })
    //判断音频播放结束
    if (offset >= duration || (duration - offset < 0.4 && target)) {
      that.setData({
        starttime: '00:00', //正在播放时长
        isOpen: false,
        offset: 0
      })
    }
  },

  timestampToDay(createTime) {
    return util.timestampToDayHkt(createTime);
  },
  
  //获取我的推荐页面
  getMyRecommentList(type) {
    var ctx = this;
    var employeeId = Number(ctx.data.eId);
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/friendscircle/queryEmpFriendCircle',
      data: {
        cusmallToken: cusmallToken,
        employeeId: employeeId,
        type: type
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        console.log(data)
        if (data && 0 === data.ret) {
          var list = data.model.list;
          for (var val of list) {
            val.disDay = ctx.timestampToDay(val.createTime)
          }
          ctx.setData({
            recommendList: list
          })
        }
      },
      fail() {

      },
      complete() { }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let cusmallToken = wx.getStorageSync('cusmallToken')
    // if (!cusmallToken){
    //   wx.navigateTo({
    //     url: '/subPackages/pages/login/login'
    //   })
    // }
    var ctx = this;
    this.setOpa();
    wx.getSystemInfo({
      success: function (t) {
        ctx.setData({
          windowHeight: t.windowHeight,
          windowWidth: t.windowWidth,
          options: options,
          eId: options.eId || wx.getStorageSync('eId') || ""
        });
      }
    })
    if (options.fromOpenId) {
      ctx.commBindPromoter(options.fromOpenId);
    }
    if (options.scene) {
      util.fetchSceneInfo(options.scene, function (res) {
        var data = res.data;
        try {
          var entity = JSON.parse(data.model.appletScene.entity);
        } catch (e) {
          entity = {};
        }
        ctx.commBindPromoter(entity.fromOpenId);
        ctx.setData({
          eId: entity.eid,
          //isSales: false,//entity.isBind 扫码进来的人目前无法 区分是否是销售员还有用户 需要用下面的进行判断 #1
        });
      });
    }
    cusmallToken = wx.getStorageSync('cusmallToken');
    app.getUserInfo(this, options, function (userInfo, res) {
      ctx.queryDetail();
      //获取我的推荐数据
      ctx.getMyRecommentList(1);

      cusmallToken = wx.getStorageSync('cusmallToken');
      var visitCardConfig = wx.getStorageSync("visitCardConfig");
      var companyInfo = wx.getStorageSync('companyInfo');
      ctx.setData({
        companyInfo: wx.getStorageSync('companyInfo'),
        skinStyleType: visitCardConfig.skinStyleType,
        mallEnable: visitCardConfig.mallEnable,
        getPhoneNumber: visitCardConfig.authTelEnable && !wx.getStorageSync('hasGetCustomMobile')
      });
      if ("" == ctx.data.address) {
        //因为和 ctx.queryDetail() 调用存在异步的问， 如果 queryDetail先执行完并且 给address设置了值 就不要重新 给默认值。
        //如果这个字段为 空说明 字段没有被设置过 ，给默认值
        ctx.setData({
          address: companyInfo.location
        });
      }
      var curUserIsEmp = wx.getStorageSync('employee');
      //判断当前用户是否是此小程序的销售员
      // ctx.userIsSales();
      wx.setStorageSync("eId", ctx.data.eId);//刷新 缓存的员工id
      if (options.scene) {//扫码 名片
        debugger
        util.fetchSceneInfo(options.scene, function (res) {
          var data = res.data;
          try {
            var entity = JSON.parse(data.model.appletScene.entity);
          } catch (e) {
            entity = {};
          }
          ctx.setData({
            eId: entity.eid,
            //isSales: false,//entity.isBind 扫码进来的人目前无法 区分是否是销售员还有用户 需要用下面的进行判断 #1
          });
          ctx.getMemberCountByEid();
          //获取推荐商品/产品
          // ctx.fetchReGoodsList();
          // ctx.userIsSales();

          wx.setStorageSync("eId", entity.eid);//员工id
          // ctx.queryDetail();
        });
      } else {
        if (undefined !== options.source && ctx.data.eId) {//用户绑定card关系
          util.addRelation(ctx.data.eId, cusmallToken, options.source);
        } else if (ctx.data.eId) {
          util.addRelation(ctx.data.eId, cusmallToken, 1);//1 默认分享
        }
        // ctx.queryDetail();
        // util.addBehaviorTrail(ctx.data.eId, 2);//查看名片 ++
        ctx.getMemberCountByEid();
        //获取推荐商品/产品
        // ctx.fetchReGoodsList();
      }
      //2 名片页底部广告
      ctx.getAdInfo(wx.getStorageSync('advertConfig'), 2);
      util.afterPageLoad(ctx);
    });
    //使用wx.createAudioContext 获取 audio
    this.audioCtx = wx.createAudioContext('myAudio');
  },
  // token获取成功后立即执行，不依赖其他数据的（look look app.js）
  onGetTokenFinish() {
    var ctx = this;
    if (!ctx.data.options.scene) {
      // ctx.queryDetail();
    }
    if (!wx.getStorageSync('userInfo')) {
      app.queryUserIdentity();
      app.getCompanyInfo().then(function () {
        ctx.setData({
          companyInfo: wx.getStorageSync('companyInfo')
        })
      });
    }
  },
  toBuildingDetail(e) {
    wx.navigateTo({ url: `../../subPackages/pages/buildingDetail/buildingDetail?productId=${e.currentTarget.dataset.productid}` })
  },
  toGift(e) {
    console.log(e.currentTarget.dataset.id)
    wx.navigateTo({ url: `../../subPackages/pages/giftManage/giftDetail/giftDetail?giftId=${e.currentTarget.dataset.id}` })
  },
  activityClick(e) {
    console.log(e.currentTarget.dataset)
    let id = e.currentTarget.dataset.id
    let productId = e.currentTarget.dataset.productid
    wx.navigateTo({
      url: `/subPackages2/pages/findHouse/activity/apply/apply?contentId=${id}&productId=${productId}`,
    })
  },
  sendMsg: function (productName) {
    var that = this
    var n = that.data.chat_content;
    var msgtosend = "";
    //获取消息内容
    var msgLen = webim.Tool.getStrBytes(msgtosend);
    var  selSess;
    if (!selSess) {
      selSess = new webim.Session(webim.SESSION_TYPE.C2C, selToID, selToID, "", Math.round(new Date().getTime() / 1000));
    }
    var isSend = true;//是否为自己发送
    var seq = -1;//消息序列，-1表示sdk自动生成，用于去重
    var random = Math.round(Math.random() * 4294967296);//消息随机数，用于去重
    var msgTime = Math.round(new Date().getTime() / 1000);//消息时间戳
    var subType = webim.C2C_MSG_SUB_TYPE.COMMON;//消息子类型
    var msg = new webim.Msg(selSess, isSend, seq, random, msgTime, userSignInfo.identifier, subType, userSignInfo.identifierNick);
    //解析文本和表情
    var expr = /\[[^[\]]{1,3}\]/mg;
    var emotions = msgtosend.match(expr);
    var text_obj;
    text_obj = new webim.Msg.Elem.Text(msgtosend);
    msg.addText(text_obj);
    var N = {
      type: 2,
      head_img: that.data.toUserSignInfo.headUrl,
      from_userinfo: that.data.userSignInfo,
      to_userinfo: that.data.toUserSignInfo, card_id: card_id,
      send: 1,
      date: "",
      EmptyNews:0,
      msg: {
        type: 0,
        context: msgtosend,
        card_id: card_id,
        from: that.data.toUserSignInfo.nickName      
      }
    };
    N.msg.context =msg;
    for (var O = [], I = 0; I < msg.elems.length; I++){
      "TIMFaceElem" == msg.elems[I].type ? O.push({
        data: msg.elems[I].content.data,
        index: msg.elems[I].content.index
      }) : "TIMTextElem" == msg.elems[I].type && O.push(msg.elems[I].content.text)
    }
    msg.elems[0].content.text = {
      type: 2,
      head_img: that.data.toUserSignInfo.headUrl,
      from_userinfo: that.data.userSignInfo,
      to_userinfo: that.data.toUserSignInfo, card_id: card_id,
      EmptyNews:0,
      msg: {
        type: 0,
        context: O,
        card_id: card_id,
        from: that.data.toUserSignInfo.nickName
      }
    };
    msg.elems[0].content.text = JSON.stringify(msg.elems[0].content.text);
    msg.elems[0].type = "TIMTextElem";
    if (msg.elems.length > 1) {
      msg.elems.splice(1, msg.elems.length - 1);
    }
   that.sendMsgState(msg);
     
   
  },
  //发送消息的状态
  sendMsgState(msg){
    
    let that = this;
    let toUserSignInfo = this.data.toUserSignInfo;
    webim.sendMsg(msg, function (t) {
    }, function (t) {
      let param={
        identifier:toUserSignInfo.identifier,
        nick:toUserSignInfo.nickName
      }
      if(t.ErrorCode==20003){
        that.accountImport(param,(res)=>{
          if(res.data.ret==0&&res.data.msg=="success"){
            that.sendMsgState(msg)
          }
         
         
        })
      }
    });
  },
  queryDetail() {//查询当前 卡片 的员工信息
    // debugger
    var ctx = this;
    cusmallToken = wx.getStorageSync('cusmallToken');
    let getCurrEmployee = wx.getStorageSync('employee');
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/employee/getEmployeeInfo',//'http://10.73.158.97:8099/applet/mobile/visitcard/employee/getEmployeeInfo',
      data: {
        cusmallToken: cusmallToken,
        eid: ctx.data.eId
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        var openid = "";
        card_id= data.model.employee.id;
        openid = data.model.employee.openid;
        
        if (data && data.model.employee && data.model.employee.deleted==false) {
          util.addRelation(ctx.data.eId, cusmallToken, 0);
          util.addBehaviorTrail(ctx.data.eId, 2);////查看名片 ++

          ctx.getNewestProduct(data.model.employee.phone,(item)=>{
            ctx.fetchSig(data.model.employee.openid, function () {
              ctx.initIM(function () {
                let productName = item?item.name:''
                if(selToID!==getCurrEmployee.openid){
                  ctx.sendMsg(productName);
                }
                
              })
            });
          })
          
          ctx.getActivity(data.model.employee.phone)
          ctx.getcouponList(data.model.employee.phone)
          ctx.getHouse(data.model.employee.phone,data.model.employee.projectId)
          ctx.getNews(data.model.employee.phone)
          data.model.employee.showPic = data.model.employee.showPic && data.model.employee.showPic.split(",") || [];
          let tel = data.model.employee.phone;
          if (data.model.employee.personalProfile) {
            var profilestr = data.model.employee.personalProfile.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' '); ctx.setData({
              test: profilestr
            })
          }

          if (data.model.employee.extend) {
            data.model.employee.extend = JSON.parse(data.model.employee.extend)
            var resData = data.model.employee.extend;
            if (resData.region) {
              ctx.setData({
                address:resData.address
              });
            }
            if (resData.locationInfo && resData.locationInfo.latitude + '' && resData.locationInfo.longitude + '') {
              ctx.setData({
                latitude: Number(resData.locationInfo.latitude),
                longitude: Number(resData.locationInfo.longitude)
              })
            }
            if (resData.locationInfo && resData.locationInfo.latitude) {
              ctx.setData({
                isLocation: true
              });
            }
            ctx.setData({
              empExtend: resData
            });
          } else { // 默认地址显示 公司地址
            ctx.setData({
              address: (ctx.data.companyInfo && ctx.data.companyInfo.location) || "",
              empExtend: {}
            });
          }
          if ("" != data.model.employee.labels) {
            data.model.employee.labels = JSON.parse(data.model.employee.labels);
          } else {
            data.model.employee.labels = [];
          }
          let showChatBtn = data.model.employee.openid&&data.model.employee.openid!=wx.getStorageSync('openId')
          ctx.setData({
            voiceTime: parseInt(data.model.employee.voiceTime),
            card: data.model.employee,
            openid,
            isThumbs: data.model.isThumbs == undefined ? false : data.model.isThumbs,
            cardStyleId: !data.model.employee.cardStyleId ? 1 : data.model.employee.cardStyleId,
            showChatBtn
          })
          app.globalData.card = data.model.employee;
        }else{
          ctx.setData({
            employeeData:{
              dimissionEmployee:data.model.employee,
              toEmployee:data.model.toEmployee
            },
            isDimission:data.model.employee.deleted
          })
        }
       
      },
      complete: function () {
        wx.hideLoading();
      }
    })
  },
  handleHouse(data,productId){
    let arr = []
    if(data&&data.length){
      data.map((item,index)=>{
        if(productId==item.productId){
          arr.unshift(item);
        } else {
          arr.push(item);
        }
      })
    }
    return arr;
  },
  getHouse(phone,projectId) {
    const that = this
    wx.request({
      url: `${cf2.default.dataCenter}/zmzj/product/${phone}/1/999`,
      data: {},
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('authName')
      },
      success: function (res) {
        
          wx.request({
            url:`${cf.config.pageDomain}/api/counselor/getProjectInfoById`,
            header: {
              'content-type': 'application/json',
            },
            data:{ projectId },
            success:function(res2){
              if(res2.data.ret==0){
                let data = res.data.data?res.data.data.list:[]
                that.setData({ houseList: that.handleHouse(data,res2.data.model.projectInfo.productId) })
              } else {
                let data = res.data.data?res.data.data.list:[]
                that.setData({ houseList: data })
              }
            }
          })
      }
    })
  },
  zan() {
    var ctx = this;
    var count = 0;
    if (ctx.data.thumbsIng) {
      return;
    }
    ctx.setData({
      thumbsIng: true
    });
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/employee/thumbsVisitCard',
      data: {
        cusmallToken: cusmallToken,
        eid: ctx.data.eId
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (ctx.data.isThumbs) {
          count = -1;
        } else {
          count = 1;
        }
        if (data && data.ret == 0) {
          ctx.setData({
            isThumbs: !ctx.data.isThumbs,
            ['card.thumbsCount']: ctx.data.card.thumbsCount + count
          })
        } else {

        }
      },
      complete: function () {
        ctx.setData({
          thumbsIng: false
        });
      }
    })
  },
  toFans: function (e) {
    console.log(e.currentTarget)
    let { productid } = e.currentTarget.dataset;
    wx.navigateTo({ url: `/subPackages/pages/fansAccessRecord/fansAccessRecord?productId=${productid}&type=employee` })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  _goback() {
    wx.navigateTo({ url:'/pages/load/load' })
  },
  open_card_detail() {
    var ctx = this;
    ctx.setData({
      ['card.open_card_detail']: !ctx.data.card.open_card_detail
    })
  },
  saveToPhone() {
    var ctx = this;
    if (wx.addPhoneContact) {
      wx.addPhoneContact({
        nickName: ctx.data.card.name,
        mobilePhoneNumber: ctx.data.card.telephone||ctx.data.card.phone,
        weChatNumber: ctx.data.card.wxAccount,
        firstName: ctx.data.card.name,
        title: ctx.data.card.post,
        organization: ctx.data.companyInfo.company,
        email: ctx.data.card.email,
        workPhoneNumber: ctx.data.card.telephone||ctx.data.card.phone,
        addressState: ctx.data.empExtend.region ? ctx.data.empExtend.region.split(',')[0] : '',
        addressCity: ctx.data.empExtend.region ? ctx.data.empExtend.region.split(',')[1] : '',
        addressStreet: ctx.data.empExtend.region ? ctx.data.empExtend.region.split(',')[2] : '',
        success() {
          util.addBehaviorTrail(ctx.data.eId, 12);
        },
        fail(e) {
          console.log(e)
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false
      })
    }

  },
  showShareMask() {
    this.setData({
      shareMask: true
    })
  },
  hideMask() {
    this.setData({
      shareMask: false
    });
  },
  card_options(e) {
    var ctx = this;
    var option = e.currentTarget.dataset.option;
    var target = e.currentTarget.dataset.target;
    var copy = e.currentTarget.dataset.copy;
    if ("copy" == option) {
      wx.setClipboardData({
        data: target,
        success: function (res) {
          wx.showToast({
            title: '复制成功',
          });
          if ("wxid" == copy) {
            util.addBehaviorTrail(ctx.data.eId, 9);
          } else if ("email" == copy) {
            util.addBehaviorTrail(ctx.data.eId, 10);
          } else if ("company" == copy) {
            util.addBehaviorTrail(ctx.data.eId, 28);
          } else if ("addr" == copy) {
            util.addBehaviorTrail(ctx.data.eId, 29);
          }
        },
        fail(e) {
          wx.showToast({
            title: '复制失败' + e.toString()
          })
        }
      })
    } else if ("call" == option) {
      util.addBehaviorTrail(ctx.data.eId, 11);
      wx.makePhoneCall({
        phoneNumber: target,
      })
    }
  },
  toSales() {
    wx.navigateTo({
      url: '/pages/sales/radar/radar',
    })
  },
  toPoster(e) {
    var ctx = this;
    util.addBehaviorTrail(ctx.data.eId, 3);
    wx.navigateTo({
      url: '/pages/canvas/index?eId=' + ctx.data.eId,
    })
  },
  
  getFansList(){
    let that = this;
    wx.request({
      url:`${cf.config.pageDomain}applet/mobile/visitcard/employee/queryFansLog`,
      header:{
        'content-type': 'application/json'
      },
      data:{
        eid: that.data.eId,
        cusmallToken: cusmallToken,
        types:1,
        pageSize:10,
        pageNo:1
      },
      success:function(res){
        that.setData({
          memberCount: res.data.count,
          mHeadImgs:res.data.fans.map(item=>item.headimgurl)
        })
      }
    })
  },
  getMemberCountByEid(){
    let that = this
    wx.request({
      url:`${cf.config.pageDomain}applet/mobile/visitcard/employee/addFansLog`,
      header:{
        'content-type': 'application/json'
      },
      data:{
        eid: that.data.eId,
        cusmallToken: cusmallToken,
        types:1
      },
      success:function(res){
        that.getFansList()
      }
    })
  },
  viewImg: function (e) { // 预览图片
    var ctx = this;
    var idx = e.currentTarget.dataset.id;
    var absoultPathPic = [];
    for (var i = 0; i < ctx.data.card.showPic.length; i++) {
      absoultPathPic.push(ctx.data.card.showPic[i]);
    }
    wx.previewImage({
      current: absoultPathPic[idx],
      urls: absoultPathPic
    })
  },
  toPlayVideo(e) {
    var ctx = this;
    wx.navigateTo({
      url: '/pages/single_video/video_play?vUrl=' + ctx.data.card.videoUrl+"?"+new Date().getTime(),
    })
  },
  updateLabNum(e) {
    var ctx = this;
    var labName = e.currentTarget.dataset.ln;
    var labNum = parseInt(e.currentTarget.dataset.labNum);
    var idx = parseInt(e.currentTarget.dataset.idx);
    ctx.setData({
      addingFlag: true,
    });
    wx.request({
      url: cf.config.pageDomain + 'applet/mobile/visitcard/employee/checkCount',
      data: {
        cusmallToken: cusmallToken,
        eid: ctx.data.eId,
        label: labName
      },
      header: {
        "Content-Type": "application/json"
      },
      success:function(res){
        if(res.data.flag&&res.data.flag=='true'){
          wx.request({
            url: cf.config.pageDomain + "/applet/mobile/visitcard/employee/addLabelsCount",
            data: {
              cusmallToken: cusmallToken,
              eid: ctx.data.eId,
              label: labName
            },
            header: {
              "Content-Type": "application/json"
            },
            success: function (res) {
              // if (res.data && 0 == res.data.ret) {
                ctx.setData({
                  ["card.labels[" + idx + "].num"]: labNum + 1,
                  ["card.labels[" + idx + "].animation"]: true
                });
                setTimeout(function () {
                  ctx.setData({
                    addingFlag: false,
                    ["card.labels[" + idx + "].animation"]: false
                  });
                }, 1000);
            }
          });
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: "每个用户每天只能对同一标签点赞一次"
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let employee = wx.getStorageSync('employee');
    if (employee) {
      this.setData({ isSales: true })
    }
    this.setData({showNavBar:true});
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function (e) {
    let employee = wx.getStorageSync('employee');
    let ctx = this;
    let title;
    this.setData({
      isSales:false,
      showNavBar:false
    })
    if (null == ctx.data.card.shareSpeech) {
      title = "你好，我是" + (ctx.data.card.company || ctx.data.companyInfo.shortName) + '的' + ctx.data.card.name;
    } else {
      title = ctx.data.card.shareSpeech;
    }
    let path = "/pages/mycard/card?eId=" + ctx.data.eId + "&source=1";
    //收集用户分享名片信息
    app.globalData.sensors.track('1021', {
       account_id: wx.getStorageSync('userId'),
        role:employee?'置业顾问':'用户'
         });
    util.addBehaviorTrail(ctx.data.eId, 3);
    //path 添加客户来源
    path += "&fromOpenId=" + ctx.data.app.globalData.myOpenid + "&fromNickName=" + ctx.data.app.globalData.userInfo.nickName + "&forwardType=page_card";
    let shareObj = {
      title: title,
      path: path,
      success: function (res) {
      },
      fail: function (res) {
      }
    };
    return shareObj;
  }
}))
